package com.ziroom.finance.rabbitmq.common.excel;

import com.ziroom.finance.rabbitmq.common.util.DateUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 导出excel
 *
 * @param <T>
 */
@Component
public class ExportExcelUtils<T> {

    private final Logger logger = LoggerFactory.getLogger(ExportExcelUtils.class);

    public void exportExcel(String title, Collection<T> dataset, OutputStream out) throws Exception {
        exportExcel(title, null, null, dataset, out, "yyyy-MM-dd");
    }

    public void exportExcel(String title, String[] headers, List<String> exportField, Collection<T> dataset, HttpServletResponse response, HttpServletRequest request) throws Exception {
        OutputStream out = explorerDeal(title, response, request);
        exportExcel(title, headers, exportField, dataset, out, "yyyy-MM-dd");
    }

    public void exportExcel(String[] headers, List<String> exportField, Collection<T> dataset,
                            OutputStream out, String pattern, String title) throws Exception {
        exportExcel(title, headers, exportField, dataset, out, pattern);
    }


    /**
     * 这是一个通用的方法，利用了JAVA的反射机制，可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
     *
     * @param title   表格标题名
     * @param headers 表格属性列名数组
     * @param dataset 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
     *                javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
     * @param out     与输出设备关联的流对象，可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern 如果有时间数据，设定输出格式。默认为"yyy-MM-dd"
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public void exportExcel(String title, String[] headers, List<String> exportField,
                            Collection<T> dataset, OutputStream out, String pattern) throws Exception {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 生成一个样式
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.BLACK.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFCellStyle style = workbook.createCellStyle(); // 样式对象
        style.setFont(font);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        // 生成并设置另一个样式
        HSSFFont font2 = workbook.createFont();
        font2.setColor(HSSFColor.BLACK.index);
        font2.setFontHeightInPoints((short) 12);
        HSSFCellStyle style2 = workbook.createCellStyle(); // 样式对象
        style2.setFont(font2);

        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平

        // 声明一个画图的顶级管理器
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 定义注释的大小和位置,详见文档
        HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
                0, 0, 0, (short) 4, 2, (short) 6, 5));
        // 设置注释内容
        comment.setString(new HSSFRichTextString("可以在POI中添加注释！"));
        // 设置注释作者，当鼠标移动到单元格上是可以在状态栏中看到该内容.
        comment.setAuthor("leno");

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍历集合数据，产生数据行
        Iterator<T> it = dataset.iterator();
        Integer index = 0;
        int num = 0;
        int j = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            if (exportField != null) {
                fields = filterField(fields, exportField);
            }

            for (short i = 0; i < fields.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style2);
                Field field = fields[i];
                String fieldName = field.getName();

                String getMethodName = "get"
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName,
                            new Class[]
                                    {});
                    Object value = getMethod.invoke(t, new Object[]{});
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    if (value instanceof Boolean) {
                        boolean bValue = (Boolean) value;
                        textValue = "true";
                        if (!bValue) {
                            textValue = "false";
                        }
                    } else if (value instanceof Date) {
                        Date date = (Date) value;
                        textValue = DateUtils.format(date,pattern);
                    } else if (value instanceof byte[]) {
                        // 有图片时，设置行高为60px;
                        row.setHeightInPoints(60);
                        // 设置图片所在列宽度为80px,注意这里单位的一个换算
                        sheet.setColumnWidth(i, (short) (35.7 * 80));
                        // sheet.autoSizeColumn(i);
                        byte[] bsValue = (byte[]) value;
                        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
                                1023, 255, (short) 6, index, (short) 6, index);
                        anchor.setAnchorType(2);
                        patriarch.createPicture(anchor, workbook.addPicture(
                                bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        if (value != null) {
                            textValue = value.toString();
                        }
                    }
                    // 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
                    if (textValue != null) {
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            HSSFRichTextString richString = new HSSFRichTextString(
                                    textValue);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (Exception e) {
                    logger.error("导出excel异常，" + e.getMessage(), e);
                }
            }
        }

        try {
            workbook.write(out);
        } catch (IOException e) {
            logger.error("导出excel异常：" + e.getMessage(), e);
        }
    }

    public Field[] filterField(Field[] qfields, List<String> exportField) {
        Field[] fields = new Field[exportField.size()];
        for (int i = 0; i < qfields.length; i++) {
            Integer index = exportField.indexOf(qfields[i].getName());
            if (index != -1) {
                fields[index] = qfields[i];
            }
        }
        return fields;
    }


    /**
     * 处理不同浏览器
     *
     * @return
     * @Author liyb58
     * @Date 2016/11/17 11:34
     */
    private OutputStream explorerDeal(String title, HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        String userAgent = request.getHeader("User-Agent");
        String downLoadName = null;
        String fileName = title + ".xls";
        OutputStream out = null;
        try {
            if (null != userAgent && userAgent.contains("MSIE")) {  //IE
                downLoadName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else if (null != userAgent && userAgent.contains("Mozilla")) { //Firefox
                downLoadName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } else {
                downLoadName = java.net.URLEncoder.encode(fileName, "UTF-8");
            }
            response.setHeader("Content-Disposition", "attachment;filename=\""
                    + downLoadName + "\"");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            out = response.getOutputStream();
        } catch (Exception e) {
            logger.error("导出excel异常，" + e.getMessage(), e);
        }
        return out;
    }

}
